<?php

class CategoryController extends FController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated users to access all actions
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		); 
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Category;

		$topCaregory = Category::model()->findAll('ParentID=0');
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		$cateDatas = array( 0 => '顶级' );
		if ( is_array( $topCaregory ) ){
			foreach( $topCaregory as $value ){
				$cateDatas[ $value['ID'] ] = $value['ZHName'] . '/' . $value['ENName'];
			}
		}
		
		$upload_dir=Yii::app()->params['uploadFile'];
		$base_upload_dir=Yii::app()->basePath.DS.$upload_dir;
		
		if(isset($_POST['Category']))
		{
			$model->attributes=$_POST['Category'];
			$file=CUploadedFile::getInstance($model,'PicPath');
			if($file){		
				$newname=date('YmdHmss',time()).'.'.$file->extensionName;
				$picpath=$upload_dir.'category'.DS.$newname;
				$picpath=str_replace(DS, '/',$picpath);
				$model->PicPath = $picpath;				
				$file->saveAs($model->PicPath);//上传到服务器	
			}				
			if($model->save())
				$this->redirect(array('index'));
		}

		$this->render('create',array(
			'model'=>$model,
			'cateDatas' => $cateDatas,
			'flagDatas' => array( '0' => '不可用' , '1' => '可用')
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($ID)
	{
		$ID=intval($ID);
		$model=new Category;
		
		$cateDatas = array( 0 => '顶级' );
		$topCaregory = Category::model()->findAll('ParentID=0');
		if ( is_array( $topCaregory ) ){
			foreach( $topCaregory as $value ){
				$cateDatas[ $value['ID'] ] = $value['ZHName'] . '/' . $value['ENName'];
			}
		}		
		
		if(!empty($ID))
		{
			$model=Category::model()->findByPk($ID);
			if(!$model->ID)
			{
				throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
			}
		}else{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
		
		$upload_dir=Yii::app()->params['uploadFile'];
		$base_upload_dir=Yii::app()->basePath.DS.$upload_dir;		
		//$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Category']))
		{
			$model->attributes=$_POST['Category'];
			$file=CUploadedFile::getInstance($model,'PicPath');
			if($file){
				$newname=date('YmdHmss',time()).'.'.$file->extensionName;
				$picpath=$upload_dir.'category'.DS.$newname;
				$picpath=str_replace(DS, '/',$picpath);
				$model->PicPath = $picpath;
				$file->saveAs($model->PicPath);//上传到服务器	
			}			
			if($model->save())
				$this->redirect(array('index'));
		}
		
		
		$this->render('update',array(
			'model'=>$model,
			'cateDatas' => $cateDatas,
			'flagDatas' => array( '0' => '不可用' , '1' => '可用')		
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($ID)
	{
		$ID=intval($ID);
		if(!empty($ID))
		{
			// we only allow deletion via POST request
			$model=new Category;
			$imgdir=Category::model()->findByPk($ID)->PicPath;
			if($imgdir && file_exists($imgdir))
			{
				unlink($imgdir);
			}
			if(Category::model()->deleteByPk($ID))
			{
				$this->redirect(array('index'));
			}
		}
		else{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
	}
	

	/**
	 * Lists all models.
	 */
	public function actionIndex( $parentID = 0 , $page = 1 )
	{
		//取得每页显示多少个
		$pageNum = Yii::app()->params['adminGirdPageNum'];
		$totalNum = Category::model()->count('ParentID=?' , array( $parentID ) );
		$pages=new CPagination($totalNum);
		$pages->pageSize=$pageNum;
		$criteria=new CDbCriteria();
		$pages->applyLimit($criteria);
		$datas = Category::model()->findAll( 'ParentID=:parentID limit :offset,:limit' , array(
			':parentID' => $parentID ,
			':offset' => $pages->currentPage*$pages->pageSize ,
			':limit' => $pages->pageSize
		) );
		foreach( $datas as &$value ){
			if ( $value['ParentID'] == 0 ){
				$value['ENName'] = '<a href="' . $this->createUrl('category/index' , array( 'parentID' => $value['ID'] ) ) . '">' . $value['ENName'] . '</a>';
				$value['ParentID'] = '无';
			} else {
				$tmp_v = Category::model()->findByPk($value['ParentID']);
				$value['ParentID'] = $value['ZHName'] = '<a href="' . $this->createUrl('category/index' , array( 'parentID' => $tmp_v['ID'] ) ) . '">' . $tmp_v['ZHName'] . '</a>';
			}
			$value = array(
				'ID' => $value['ID'],
				'ENName' => $value['ENName'],
				'ZHName' => $value['ZHName'],
				'ParentID' => $value['ParentID'],
				'PicPath' => '<img src="' . $value['PicPath'] .'" size="60" width="90" />',
				'Flag' => $value['Flag'] == 1 ? '是' : '否' ,
			);
			//var_dump($value);
		}
		//var_dump($datas);
		$this->render('index',array(
			'totalNum' => $totalNum ,
			'datas' => $datas,
			'pages' => $pages
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Category('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Category']))
			$model->attributes=$_GET['Category'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Category::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='category-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
